package com.shoppingwebsite.controller;

import com.shoppingwebsite.domain.Result;
import com.shoppingwebsite.domain.YtUser;
import com.shoppingwebsite.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/registerUser")
    public Result registerJudge(YtUser user){
        //注册用户
        int f = userService.add(user);
        Result result=new Result();
        if(f>0){
            result.setFlag(true);
            result.setInfo("用户注册成功");
        }else {
            result.setFlag(false);
            result.setInfo("用户注册失败");
        }

        return result;
    }

    @PostMapping("/loginUser")
    public Result login(YtUser user, HttpSession session){
        String userName = user.getUsername();
        String password = user.getPassword();
        System.out.println(userName);
        System.out.println(password);

        Result result=new Result();
        //空值
        if(userName==""||password==""){
            result.setFlag(false);
            result.setInfo("请不要为空");
            return result;
        }
        YtUser user1 = userService.select(userName);
        //不存在该用户
        if(user1==null){
            result.setFlag(false);
            result.setInfo("该用户不存在");
            return result;
        }else{
            //密码错误
            if(!password.equals(user1.getPassword())){
                result.setFlag(false);
                result.setInfo("密码错误");
                return result;
            }
        }

        //存储用户信息
        session.setAttribute("loginUser",user1.getId());


        //登录成功
        result.setFlag(true);
        result.setInfo("用户登录成功");
        return result;
    }

    @PostMapping("/exitUser")
    public void login(HttpServletRequest request, HttpServletResponse response){
        //移除用户信息
        request.getSession().setAttribute("loginUser",null);
    }
}
